import json

from src.tools.chain import gen_chain
from src.tools.excel_to_md import excel2md
from src.tools.extract_jsonstring import re_json_string
from src.gen_file.prompt import BPRSolidPrompt
from src.tools.dms_operator import dmsoperator
from src.tools.information_exchange import pub_gen
from src.tools.split_string import split_sub_string


class GenSolidBPRfile:
    def __init__(self):
        self.prompt = BPRSolidPrompt()

    # 解析批记录文件,提取要修改的段落和表格
    def parse_BPRjsonfile(self, json_data: dict):
        file_pubinfo = {
            "filePath": json_data["filePath"],
            "isHighlight": True,
            "editInfos": []
        }

        parainfo = []
        for para in json_data["paragraphInfos"]:
            is_highlightcolor_para = False
            para_text = ""
            for textinfo in para["textInfos"]:
                if textinfo["subSuperscript"] == 2:
                    para_text += f'<sub>{textinfo["text"]}</sub>'
                else:
                    para_text += textinfo["text"]
                if textinfo["highlightColor"] != "0, 0, 0, 0":
                    is_highlightcolor_para = True
            if is_highlightcolor_para:
                para_dict = {
                    "index": para["index"],
                    "sectionIndex": para["sectionIndex"],
                    "bodyChildIndex": para["bodyChildIndex"],
                    "text": para_text
                }
                parainfo.append(para_dict)

        tableinfo = []
        for table in json_data["tableInfos"]:
            # 标注高亮是修改部分, 以table为单位进行修改
            is_highlightcolor_table = False
            table_dict = {
                "index": table["index"],
                "sectionIndex": table["sectionIndex"],
                "bodyChildIndex": table["bodyChildIndex"],
                "tableCellInfos": []
            }
            for cell in table["tableCellInfos"]:
                cell_dict = {
                    "rowIndex": cell["rowIndex"],
                    "columnIndex": cell["columnIndex"],
                    "paragraphInfos": []
                }
                for para in cell["paragraphInfos"]:
                    para_text = ""
                    for textinfo in para["textInfos"]:
                        if textinfo["subSuperscript"] == 2:
                            para_text += f'<sub>{textinfo["text"]}</sub>'
                        else:
                            para_text += textinfo["text"]
                        if textinfo["highlightColor"] != "0, 0, 0, 0":
                            is_highlightcolor_table = True
                    para_dict = {
                        "index": para["index"],
                        "sectionIndex": para["sectionIndex"],
                        "bodyChildIndex": para["bodyChildIndex"],
                        "text": para_text
                    }
                    cell_dict["paragraphInfos"].append(para_dict)
                table_dict["tableCellInfos"].append(cell_dict)
            if is_highlightcolor_table:
                tableinfo.append(table_dict)
        return file_pubinfo, parainfo, tableinfo

    # 找到流式输出内容
    def find_key_values(self, target_key,data):
        found_values = []
        if isinstance(data, dict):
            for key, value in data.items():
                if key == target_key and value:
                    found_values.append(value)
                found_values.extend(self.find_key_values(target_key, value))
        elif isinstance(data, list):
            for item in data:
                found_values.extend(self.find_key_values(target_key, item))
        return found_values

    # 利用生成链，生成要修改的内容
    def gen_BPRfile_para_table(self, content, extract_text, task_id, BPRfile):
        revise_BPRtext_query = self.prompt.gen_file_prompt(orig_BPRtext=json.dumps(content, ensure_ascii=False),
                                                          SOPtext=extract_text)
        # print("-" * 100)
        # print(revise_BPRtext_query)
        # print("-" * 100)
        revise_BPRtext = gen_chain(revise_BPRtext_query)
        try:
            revise_BPRtext = re_json_string(revise_BPRtext)
            print(revise_BPRtext)
            revise_BPRtext_dict = json.loads(revise_BPRtext)
        except:
            print("json解析失败")
            revise_BPRtext_dict = content
        text_key = self.find_key_values("text", revise_BPRtext_dict)
        for msg in text_key:
            pub_gen(task_id, msg, BPRfile.get("docId"), BPRfile.get("taskDocId"))
        return revise_BPRtext_dict


    def gen_BPRfile(self, content_files: list, BPRfile: dict, template_infos: list, task_id: str):
        bprfile_jsondata = dmsoperator.get_jsonfile(BPRfile.get("realPath"))
        SOP_query, SOP_content_file_id, supplier_content_file_id, extract_text1, extract_text2, extract_supplier_text = "", "", "", "", "", ""
        for bpr_oper in ["批生产记录", "批包装记录"]:
            if bpr_oper in BPRfile.get("documentName"):
                if bpr_oper == "批生产记录":
                    SOP_query = "生产操作及工艺条件"
                elif bpr_oper == "批包装记录":
                    SOP_query = "包装操作及工艺条件"
                break

        for content_file in content_files:
            if "工艺规程" in content_file.get("documentName"):
                SOP_content_file_id = content_file.get("realPath")

            if "供应商" in content_file.get("documentName"):
                supplier_content_file_id = content_file.get("realPath")

        if SOP_content_file_id:
            SOPtext = dmsoperator.get_fileconversion(file_id=SOP_content_file_id, file_type_num=4).replace(
                'style="text-align: center;"', "").replace('style="text-align: left;"', "").replace(
                'style="text-align: right;"', "")
            # 提取除工艺操作外的内容
            extract_query1 = self.prompt.extract_SOPinfo_prompt1(SOPtext)
            extract_text1 = gen_chain(extract_query1)
            pub_gen(task_id, extract_text1, BPRfile.get("docId"), BPRfile.get("taskDocId"))
            print(extract_text1)
            extract_query2 = self.prompt.extract_SOPinfo_prompt2(query=SOP_query, article=SOPtext)
            extract_text2 = gen_chain(extract_query2)
            pub_gen(task_id, extract_text2, BPRfile.get("docId"), BPRfile.get("taskDocId"))
            print(extract_text2)

        if supplier_content_file_id:
            if supplier_content_file_id.endswith('.xlsx'):
                suppliertext = excel2md(supplier_content_file_id)
            else:
                suppliertext = dmsoperator.get_fileconversion(file_id=supplier_content_file_id, file_type_num=4).replace('style="text-align: center;"', "").replace('style="text-align: left;"', "").replace('style="text-align: right;"', "")
            extract_supplier_query = self.prompt.extract_supplierinfo_prompt1(query=extract_text1, article=suppliertext)
            extract_supplier_text = gen_chain(extract_supplier_query)
            pub_gen(task_id, extract_supplier_text, BPRfile.get("docId"), BPRfile.get("taskDocId"))
            print(extract_supplier_text)

        extract_text = extract_text1 + "\n" + extract_text2 + "\n" + extract_supplier_text
        print(extract_text)
        file_pubinfo, parainfo, tableinfo = self.parse_BPRjsonfile(bprfile_jsondata)

        gen_filename = "生成的文件"
        table_i = -1
        # 修改段落
        for i, para in enumerate(parainfo):
            # if not template_infos[i]["source"]:
            #     revise_BPRtext_dict = self.gen_BPRfile_para_table(para, extract_text, task_id, BPRfile)
            # else:
            #     revise_BPRtext_dict = self.gen_BPRfile_para_table_temp(para, extract_text, template_infos[i]["source"], task_id, BPRfile)
            revise_BPRtext_dict = self.gen_BPRfile_para_table(para, extract_text, task_id, BPRfile)
            textinfo_list = split_sub_string(revise_BPRtext_dict["text"])
            textinfos = []
            for textinfo_index, textinfo in enumerate(textinfo_list):
                textinfo_dict = {
                    "paragraphChildIndex": textinfo_index,
                    "paraChildType": 0,
                    "content": textinfo.get("content"),
                    "subSuperScript": textinfo.get("subSuperScript")
                }
                textinfos.append(textinfo_dict)
            edit_dict = {
                "index": revise_BPRtext_dict["index"],
                "sectionIndex": revise_BPRtext_dict["sectionIndex"],
                "bodyChildIndex": revise_BPRtext_dict["bodyChildIndex"],
                "operationType": 1,
                "paragraphInfo": {
                    "paragraphChildInfos": textinfos,
                    "referenceParagraphType": 2
                }
            }
            dele_edit_dict = {
                "index": revise_BPRtext_dict["index"],
                "sectionIndex": revise_BPRtext_dict["sectionIndex"],
                "bodyChildIndex": revise_BPRtext_dict["bodyChildIndex"],
                "operationType": 2
            }
            if i == 0:
                gen_filename = revise_BPRtext_dict["text"]
            file_pubinfo["editInfos"].append(edit_dict)
            file_pubinfo["editInfos"].append(dele_edit_dict)
            table_i = i

        # 修改表格
        for table in tableinfo:
            # 以table为单位进行修改
            table_i += 1
            # if not template_infos[table_i]["source"]:
            #     revise_BPRtext_dict = self.gen_BPRfile_para_table(table, extract_text, task_id, BPRfile)
            # else:
            #     revise_BPRtext_dict = self.gen_BPRfile_para_table(table, extract_text, template_infos[table_i]["source"], task_id, BPRfile)
            revise_BPRtext_dict = self.gen_BPRfile_para_table(table, extract_text, task_id, BPRfile)
            # 判断生成的表格行数和原表格行数是否一致
            # 一致，直接修改，不一致，删除表格，重新生成
            if len(revise_BPRtext_dict["tableCellInfos"]) == len(table["tableCellInfos"]):
                table_dict = {
                    "index": revise_BPRtext_dict["index"],
                    "sectionIndex": revise_BPRtext_dict["sectionIndex"],
                    "bodyChildIndex": revise_BPRtext_dict["bodyChildIndex"],
                    "operationType": 0,
                    "tableInfo": {
                        "cellEditInfos": []
                    }
                }
                for cell in revise_BPRtext_dict["tableCellInfos"]:
                    cell_dict = {
                        "rowIndex": cell["rowIndex"],
                        "columnIndex": cell["columnIndex"],
                        "cellChildInfos": []
                    }
                    for para in cell["paragraphInfos"]:
                        textinfo_list = split_sub_string(para["text"])
                        textinfos = []
                        for textinfo_index, textinfo in enumerate(textinfo_list):
                            textinfo_dict = {
                                "paragraphChildIndex": textinfo_index,
                                "paraChildType": 0,
                                "content": textinfo.get("content"),
                                "subSuperScript": textinfo.get("subSuperScript")
                            }
                            textinfos.append(textinfo_dict)
                        para_dict = {
                            "index": para["index"],
                            "sectionIndex": para["sectionIndex"],
                            "bodyChildIndex": para["bodyChildIndex"],
                            "operationType": 1,
                            "paragraphInfo": {
                                "paragraphChildInfos": textinfos,
                                "referenceParagraphType": 2
                            }
                        }
                        dele_para_dict = {
                            "index": para["index"],
                            "sectionIndex": para["sectionIndex"],
                            "bodyChildIndex": para["bodyChildIndex"],
                            "operationType": 2
                        }
                        cell_dict["cellChildInfos"].append(para_dict)
                        cell_dict["cellChildInfos"].append(dele_para_dict)
                    table_dict["tableInfo"]["cellEditInfos"].append(cell_dict)
                file_pubinfo["editInfos"].append(table_dict)

            else:
                # 先插入表格
                max_row = -1
                max_column = -1
                for cell in revise_BPRtext_dict["tableCellInfos"]:
                    max_row = max(cell["rowIndex"], max_row)
                    max_column = max(cell["columnIndex"], max_column)
                row_num = max_row + 1
                column_num = max_column + 1
                table_dict = {
                    "index": revise_BPRtext_dict["index"],
                    "sectionIndex": revise_BPRtext_dict["sectionIndex"],
                    "bodyChildIndex": revise_BPRtext_dict["bodyChildIndex"],
                    "operationType": 1,
                    "tableInfo": {
                        "tableInsertInfo": {
                            "rowCount": row_num,
                            "columnCount": column_num,
                            "cellInsertInfos": []
                        }
                    }
                }
                for cell in revise_BPRtext_dict["tableCellInfos"]:
                    cell_dict = {
                        "rowIndex": cell["rowIndex"],
                        "columnIndex": cell["columnIndex"],
                        "cellInsertContentInfos": []
                    }
                    for para in cell["paragraphInfos"]:
                        textinfo_list = split_sub_string(para["text"])
                        textinfos = []
                        for textinfo_index, textinfo in enumerate(textinfo_list):
                            textinfo_dict = {
                                "paragraphChildIndex": textinfo_index,
                                "paraChildType": 0,
                                "content": textinfo.get("content"),
                                "subSuperScript": textinfo.get("subSuperScript")
                            }
                            textinfos.append(textinfo_dict)
                        para_dict = {
                            "index": para["index"],
                            "paragraphInfo": {
                                "paragraphChildInfos": textinfos,
                            }
                        }
                        cell_dict["cellInsertContentInfos"].append(para_dict)
                    table_dict["tableInfo"]["tableInsertInfo"]["cellInsertInfos"].append(cell_dict)
                file_pubinfo["editInfos"].append(table_dict)
                # 再删除表格
                dele_table = {
                    "index": revise_BPRtext_dict["index"],
                    "sectionIndex": revise_BPRtext_dict["sectionIndex"],
                    "bodyChildIndex": revise_BPRtext_dict["bodyChildIndex"],
                    "operationType": 2,
                }
                file_pubinfo["editInfos"].append(dele_table)


        print("-"*200)
        file_pubinfo_json = json.dumps(file_pubinfo, indent=4, ensure_ascii=False)
        print(file_pubinfo_json)
        # # 保存修改的json文件
        # edit_SOPjsonfile_path = f"修改.json"
        # with open(edit_SOPjsonfile_path, "w", encoding="utf-8") as f:
        #     f.write(file_pubinfo_json)
        print("-"*200)
        # 修改文件
        gen_res = dmsoperator.post_edit_file_v2(file_pubinfo)
        return gen_res["data"], gen_filename+".docx"

